<template>
  <view class="seckill-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-title">秒杀活动</view>
      <view class="header-tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index"
          :class="['tab-item', { active: activeTab === index }]"
          @click="switchTab(index)"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>

    <!-- 活动列表 -->
    <view class="activity-list" v-if="activeTab === 0">
      <view 
        v-for="(activity, index) in activities" 
        :key="activity.id"
        class="activity-card"
        @click="goToActivityDetail(activity.id)"
      >
        <!-- 活动状态标签 -->
        <view class="status-tag" :class="getStatusClass(activity.status)">
          {{ getStatusText(activity.status) }}
        </view>
        
        <!-- 活动信息 -->
        <view class="activity-info">
          <view class="activity-title">{{ activity.title }}</view>
          <view class="activity-desc">{{ activity.description }}</view>
          
          <!-- 倒计时 -->
          <view class="countdown" v-if="activity.status === 'ongoing'">
            <text class="countdown-label">距结束还剩：</text>
            <view class="countdown-time">
              <text class="time-item">{{ activity.countdown.hours }}</text>
              <text class="time-separator">:</text>
              <text class="time-item">{{ activity.countdown.minutes }}</text>
              <text class="time-separator">:</text>
              <text class="time-item">{{ activity.countdown.seconds }}</text>
            </view>
          </view>
          
          <!-- 活动时间 -->
          <view class="activity-time">
            <text class="time-label">活动时间：</text>
            <text class="time-value">{{ formatTime(activity.startTime) }} - {{ formatTime(activity.endTime) }}</text>
          </view>
        </view>
        
        <!-- 商品预览 -->
        <view class="products-preview" v-if="activity.products && activity.products.length">
          <view 
            v-for="(product, pIndex) in (activity.products || []).slice(0, 3)" 
            :key="product.id"
            class="product-item"
          >
            <image :src="product.image" class="product-image" mode="aspectFill" />
            <view class="product-info">
              <view class="product-name">{{ product.name }}</view>
              <view class="product-price">
                <text class="seckill-price">¥{{ product.seckillPrice }}</text>
                <text class="original-price">¥{{ product.originalPrice }}</text>
              </view>
            </view>
          </view>
          <view v-if="(activity.products || []).length > 3" class="more-products">
            +{{ (activity.products || []).length - 3 }}个商品
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="action-buttons">
          <button 
            v-if="activity.status === 'upcoming'" 
            class="btn-remind"
            @click.stop="setReminder(activity.id)"
          >
            设置提醒
          </button>
          <button 
            v-if="activity.status === 'ongoing'" 
            class="btn-seckill"
            @click.stop="goToSeckill(activity.id)"
          >
            立即抢购
          </button>
          <button 
            v-if="activity.status === 'ended'" 
            class="btn-ended"
            disabled
          >
            已结束
          </button>
        </view>
      </view>
    </view>

    <!-- 我的秒杀 -->
    <view class="my-seckill" v-if="activeTab === 1">
      <view class="empty-state" v-if="!mySeckills || mySeckills.length === 0">
        <image src="/static/images/empty-seckill.png" class="empty-image" />
        <view class="empty-text">暂无秒杀记录</view>
        <button class="btn-go-seckill" @click="activeTab = 0">去秒杀</button>
      </view>
      
      <view v-else class="my-seckill-list">
        <view 
          v-for="(item, index) in mySeckills" 
          :key="item.id"
          class="my-seckill-item"
        >
          <image :src="item.productImage" class="product-image" mode="aspectFill" />
          <view class="item-info">
            <view class="product-name">{{ item.productName }}</view>
            <view class="seckill-info">
              <text class="seckill-price">¥{{ item.seckillPrice }}</text>
              <text class="quantity">x{{ item.quantity }}</text>
            </view>
            <view class="order-status" :class="getOrderStatusClass(item.status)">
              {{ getOrderStatusText(item.status) }}
            </view>
          </view>
          <view class="item-actions">
            <button 
              v-if="item.status === 'paid'" 
              class="btn-detail"
              @click="goToOrderDetail(item.orderId)"
            >
              查看订单
            </button>
            <button 
              v-if="item.status === 'unpaid'" 
              class="btn-pay"
              @click="goToPay(item.orderId)"
            >
              立即支付
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && activeTab === 0">
      <button class="btn-load-more" @click="loadMore" :disabled="loading">
        {{ loading ? '加载中...' : '加载更多' }}
      </button>
    </view>
  </view>
</template>

<script>
import { getSeckillList, getMySeckills, setSeckillReminder } from '@/api/seckill'

export default {
  data() {
    return {
      activeTab: 0,
      tabs: [
        { name: '秒杀活动', key: 'activities' },
        { name: '我的秒杀', key: 'my-seckill' }
      ],
      activities: [],
      mySeckills: [],
      loading: false,
      hasMore: true,
      pageNum: 1,
      pageSize: 10
    }
  },
  
  onLoad() {
    this.loadActivities()
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.activeTab === 0 && this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  methods: {
    // 切换标签
    switchTab(index) {
      this.activeTab = index
      if (index === 0) {
        this.loadActivities()
      } else {
        this.loadMySeckills()
      }
    },
    
    // 加载秒杀活动
    async loadActivities() {
      try {
        this.loading = true
        const res = await getSeckillList({
		
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
		console.log(res)
        
        const activities = res.rows || []
        // 添加倒计时
        activities.forEach(activity => {
          if (activity.status === 'ongoing') {
            activity.countdown = this.calculateCountdown(activity.endTime)
          }
        })
        
        if (this.pageNum === 1) {
          this.activities = activities
        } else {
          this.activities = this.activities.concat(activities)
        }
        
        this.hasMore = activities.length === this.pageSize
      } catch (error) {
        console.error('加载秒杀活动失败:', error)
        this.$modal.msgError('加载失败')
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 加载我的秒杀
    async loadMySeckills() {
      try {
        const res = await getMySeckills()
        this.mySeckills = res.data || []
      } catch (error) {
        console.error('加载我的秒杀失败:', error)
        this.$modal.msgError('加载失败')
      }
    },
    
    // 加载更多
    loadMore() {
      if (!this.loading && this.hasMore) {
        this.pageNum++
        this.loadActivities()
      }
    },
    
    // 刷新数据
    refreshData() {
      this.pageNum = 1
      this.hasMore = true
      if (this.activeTab === 0) {
        this.loadActivities()
      } else {
        this.loadMySeckills()
      }
    },
    
    // 计算倒计时
    calculateCountdown(endTime) {
      const now = new Date().getTime()
      const end = new Date(endTime).getTime()
      const diff = Math.max(0, end - now)
      
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      
      return {
        hours: hours.toString().padStart(2, '0'),
        minutes: minutes.toString().padStart(2, '0'),
        seconds: seconds.toString().padStart(2, '0')
      }
    },
    
    // 格式化时间
    formatTime(time) {
      const date = new Date(time)
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const statusMap = {
        upcoming: 'status-upcoming',
        ongoing: 'status-ongoing',
        ended: 'status-ended'
      }
      return statusMap[status] || 'status-default'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        upcoming: '即将开始',
        ongoing: '进行中',
        ended: '已结束'
      }
      return statusMap[status] || '未知'
    },
    
    // 获取订单状态样式
    getOrderStatusClass(status) {
      const statusMap = {
        unpaid: 'status-unpaid',
        paid: 'status-paid',
        shipped: 'status-shipped',
        completed: 'status-completed'
      }
      return statusMap[status] || 'status-default'
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        unpaid: '待支付',
        paid: '已支付',
        shipped: '已发货',
        completed: '已完成'
      }
      return statusMap[status] || '未知'
    },
    
    // 跳转到活动详情
    goToActivityDetail(activityId) {
      console.log('=== 点击秒杀活动卡片 ===')
      console.log('活动ID:', activityId)
      
      // 显示点击提示
      uni.showToast({
        title: `点击了秒杀活动${activityId}`,
        icon: 'success',
        duration: 1500
      })
      
      // 延迟跳转
      setTimeout(() => {
        console.log('准备跳转到秒杀详情页...')
        uni.navigateTo({
          url: `/pages/seckill/detail?id=${activityId}`,
          success: (res) => {
            console.log('跳转成功:', res)
          },
          fail: (error) => {
            console.error('跳转失败:', error)
            uni.showToast({
              title: '跳转失败: ' + error.errMsg,
              icon: 'none',
              duration: 3000
            })
          }
        })
      }, 1000)
    },
    
    // 跳转到秒杀页面
    goToSeckill(activityId) {
      // 直接跳转到活动详情页面
      uni.navigateTo({
        url: `/pages/seckill/detail?id=${activityId}`
      })
    },
    
    // 设置提醒
    async setReminder(activityId) {
      try {
        const response = await setSeckillReminder({
          activityId: activityId
        })
        
        if (response.code === 200) {
          this.$modal.msgSuccess('提醒设置成功')
        } else {
          this.$modal.msgError(response.message || '设置失败')
        }
      } catch (error) {
        console.error('设置提醒失败:', error)
        this.$modal.msgError('设置提醒失败')
      }
    },
    
    // 跳转到订单详情
    goToOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${orderId}`
      })
    },
    
    // 跳转到支付页面
    goToPay(orderId) {
      uni.navigateTo({
        url: `/pages/payment/index?orderId=${orderId}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.seckill-container {
  min-height: 100vh;
  background: #f5f6f7;
}

.header {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
  padding: 20rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20rpx;
  }
  
  .header-tabs {
    display: flex;
    justify-content: center;
    gap: 40rpx;
    
    .tab-item {
      padding: 16rpx 32rpx;
      border-radius: 32rpx;
      font-size: 28rpx;
      transition: all 0.3s;
      
      &.active {
        background: rgba(255, 255, 255, 0.2);
        font-weight: bold;
      }
    }
  }
}

.activity-list {
  padding: 20rpx;
}

.activity-card {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  position: relative;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .status-tag {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    padding: 8rpx 16rpx;
    border-radius: 16rpx;
    font-size: 24rpx;
    color: white;
    
    &.status-upcoming {
      background: #ff9500;
    }
    
    &.status-ongoing {
      background: #ff3b30;
    }
    
    &.status-ended {
      background: #8e8e93;
    }
  }
  
  .activity-info {
    margin-bottom: 30rpx;
    
    .activity-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .activity-desc {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 20rpx;
    }
    
    .countdown {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;
      
      .countdown-label {
        font-size: 26rpx;
        color: #666;
        margin-right: 10rpx;
      }
      
      .countdown-time {
        display: flex;
        align-items: center;
        
        .time-item {
          background: #ff3b30;
          color: white;
          padding: 8rpx 12rpx;
          border-radius: 8rpx;
          font-size: 24rpx;
          font-weight: bold;
          min-width: 40rpx;
          text-align: center;
        }
        
        .time-separator {
          margin: 0 8rpx;
          color: #ff3b30;
          font-weight: bold;
        }
      }
    }
    
    .activity-time {
      font-size: 24rpx;
      color: #999;
      
      .time-label {
        margin-right: 10rpx;
      }
    }
  }
  
  .products-preview {
    display: flex;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .product-item {
      flex: 1;
      text-align: center;
      
      .product-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
        margin-bottom: 10rpx;
      }
      
      .product-info {
        .product-name {
          font-size: 24rpx;
          color: #333;
          margin-bottom: 8rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .product-price {
          .seckill-price {
            font-size: 26rpx;
            color: #ff3b30;
            font-weight: bold;
            margin-right: 8rpx;
          }
          
          .original-price {
            font-size: 22rpx;
            color: #999;
            text-decoration: line-through;
          }
        }
      }
    }
    
    .more-products {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 120rpx;
      height: 120rpx;
      background: #f5f6f7;
      border-radius: 12rpx;
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .action-buttons {
    text-align: center;
    
    button {
      padding: 20rpx 60rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      border: none;
      
      &.btn-remind {
        background: #ff9500;
        color: white;
      }
      
      &.btn-seckill {
        background: #ff3b30;
        color: white;
      }
      
      &.btn-ended {
        background: #8e8e93;
        color: white;
      }
    }
  }
}

.my-seckill {
  padding: 20rpx;
  
  .empty-state {
    text-align: center;
    padding: 100rpx 0;
    
    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 40rpx;
    }
    
    .btn-go-seckill {
      background: #ff3b30;
      color: white;
      padding: 20rpx 60rpx;
      border-radius: 40rpx;
      border: none;
    }
  }
  
  .my-seckill-item {
    background: white;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    padding: 30rpx;
    display: flex;
    align-items: center;
    
    .product-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
    }
    
    .item-info {
      flex: 1;
      
      .product-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .seckill-info {
        margin-bottom: 10rpx;
        
        .seckill-price {
          font-size: 26rpx;
          color: #ff3b30;
          font-weight: bold;
          margin-right: 20rpx;
        }
        
        .quantity {
          font-size: 24rpx;
          color: #666;
        }
      }
      
      .order-status {
        font-size: 24rpx;
        
        &.status-unpaid {
          color: #ff9500;
        }
        
        &.status-paid {
          color: #34c759;
        }
        
        &.status-shipped {
          color: #007aff;
        }
        
        &.status-completed {
          color: #8e8e93;
        }
      }
    }
    
    .item-actions {
      button {
        padding: 16rpx 32rpx;
        border-radius: 32rpx;
        font-size: 24rpx;
        border: none;
        
        &.btn-detail {
          background: #f5f6f7;
          color: #666;
        }
        
        &.btn-pay {
          background: #ff3b30;
          color: white;
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 40rpx;
  
  .btn-load-more {
    background: #f5f6f7;
    color: #666;
    padding: 20rpx 60rpx;
    border-radius: 40rpx;
    border: none;
    font-size: 28rpx;
    
    &:disabled {
      opacity: 0.6;
    }
  }
}
</style> 